package com.presto.directo.base

import android.app.Activity
import android.app.Dialog
import android.os.Bundle
import android.view.View
import android.view.WindowManager
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentActivity
import com.presto.directo.R
import com.presto.directo.utils.*
import es.dmoral.toasty.Toasty
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.internal.functions.Functions
import kotlinx.coroutines.*
import java.util.concurrent.*

open class BaseFragment : Fragment(), CoroutineScope by MainScope() {

    val mActivity: FragmentActivity by lazy { requireActivity() }

    private lateinit var progress: Dialog

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initEvent()
    }

    open fun initEvent() {}

    fun showProgress(cancelable: Boolean = false) {
        if (!this::progress.isInitialized) {
            progress = Dialog(mActivity, R.style.BaseDialog)
            progress.window?.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND)
            progress.setContentView(R.layout.layout_progress)
            progress.setCanceledOnTouchOutside(false)
        }
        progress.setCancelable(cancelable)
        progress.show()
    }

    fun dismissProgress() {
        if (this::progress.isInitialized && progress.isShowing) {
            progress.hide()
        }
    }

    fun toast(msg: CharSequence?) {
        if (msg.isNullOrBlank()) return
        Toasty.info(mActivity, msg, Toasty.LENGTH_SHORT).show()
    }

    override fun onDestroyView() {
        super.onDestroyView()
        if (this::progress.isInitialized) {
            progress.dismiss()
        }
        cancel()
    }
}